import {Component, OnInit} from '@angular/core';
import {AdminService} from '../admin.service';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {AdminPwdMoudel} from '../admin-pwd-moudel';
import {NzMessageService} from 'ng-zorro-antd';

@Component({
    selector: 'app-list',
    templateUrl: './list.component.html',
})
export class ListComponent implements OnInit {
    validateForm: FormGroup;
    modelVisible = false;

    currentPage = 1;
    total = 0;
    data = [];
    pagesize = 10;

    adminMoudel: AdminPwdMoudel = new AdminPwdMoudel();

    constructor(
        private adminService: AdminService,
        private fb: FormBuilder,
        private msg: NzMessageService) {
        this.validateForm = this.fb.group({
            id: [0],
            pwd: ['', Validators.required],
        });
    }

    ngOnInit() {
        this.getlist(this.currentPage);
    }

    getlist($event) {
        this.adminService.getAdminList($event - 1).subscribe(res => {
            this.data = res['list'];
            this.total = res['totalElement'];
            this.pagesize = res['pageSize'];
            this.currentPage = $event;
        });
    }

    delAdmin(admin) {
        const index = this.data.indexOf(admin);
        this.data = [...this.data.slice(0, index), ...this.data.slice(index + 1, this.data.length)];
        this.adminService.delAdmin(admin.id).subscribe(res => {
            this.msg.success('删除成功');
        }, __ => {
            this.adminService.getAdminList(this.currentPage);
        });
    }

    /**
     * 显示修改密码
     */
    showModal(id) {
        this.modelVisible = true;
        this.adminMoudel['id'] = id;
        this.validateForm.patchValue({
            pwd: '',
        });
    }

    /**
     * 关闭修改密码
     */
    closeModal() {
        this.modelVisible = false;
    }

    /**
     * 修改密码
     */
    submit() {
        this.modelVisible = true;
        const res = this.validateForm.value;
        // this.adminMoudel['id'] = res['id'];
        this.adminMoudel['pwd'] = res['pwd'];

        this.adminService.changePwd(this.adminMoudel['id'], this.adminMoudel['pwd']).subscribe(__ => {
            this.msg.success('修改成功');
            this.closeModal();
        }, e => {
            console.error(e);
        });
    }
}
